package com.sh.sales.happysales.app.utils;

import android.content.Context;
import android.provider.Settings;
import android.util.Log;

import com.sh.sales.happysales.app.AppData;
import com.sh.sales.happysales.datautils.LocalTokenUtils;
import com.sh.sales.happysales.datautils.LocalUserInfoUtils;
import com.sh.polymedicine.happysale.net.entity.UserToken;
import com.sh.sales.happysales.service.LoginObserable;
import com.sh.polymedicine.happysale.result.UserInfoResult;
import com.sh.polymedicine.happysale.service.envelop.HappySaleManager;
import com.sh.sales.happysales.view.NewToast;

import rx.Subscriber;

/**
 * Created by zhouyucheng on 2017/9/26.
 */

public class LoginUtil {
    private static LoginUtil mLoginUtil;
    private static String TAG = "LoginUtil";
    private static Subscriber<UserToken> mUserSubscriber;
    private static Subscriber<UserInfoResult> mUserInfoSubscriber;
    private static Context mContext;
    private static int loginPosion;
    private static String deviceId;

    public static LoginUtil getInstance() {
        if (mLoginUtil == null) {
            mLoginUtil = new LoginUtil();
        }
        return mLoginUtil;
    }

    public void catchUserInfo(UserToken token, Context mContext, int loginPosion) {
        this.mContext = mContext;
        this.loginPosion = loginPosion;
        deviceId = Settings.Secure.getString(
                mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
        Log.i(TAG, "catchUserInfo: " + deviceId);
        if (1 == loginPosion) {
            userCodeGetToken(token.getCode());
        } else {
            UserToken tempToken = wirteToken(token, token.getCode()); //发布
            //  UserToken tempToken = wirteToken(localToken(), code);
            getMyInfo(tempToken);
        }

    }

    private UserToken localToken() {
        int userId = 49;
        String accessToken = "kQHLL3Rkc3d2OXpEUjCRHJ4AgzMl2bCD";
        String reflashToken = "G36awH1qapeti5LA8xNOOiDII0h4Su9r";
        String signKey = "sky@w0rth-HighTO";
        String deviceId = "864184030251067";
        UserToken u = new UserToken();
        u.setAccessToken(accessToken);
        u.setReflashToken(reflashToken);
        u.setSignKey(signKey);
        u.setUserId(userId);
        return u;
    }


    private static void userCodeGetToken(final String code) {
        if (mUserSubscriber != null) {
            if (!mUserSubscriber.isUnsubscribed()) {
                mUserSubscriber.unsubscribe();
            }
        }
        mUserSubscriber = new Subscriber<UserToken>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())) {
                    String message = e.getCause().getCause().getMessage();
                    NewToast.makeText(mContext, message);
                    int ret = Integer.valueOf(e.getCause().getMessage());
                    if (ret >= 100 && ret < 200) {
                        LoginOutUtil.logOut(mContext);
                    }
                } else if (HappySaleManager.DATA_NULL.equals(e.getMessage())) {
                    NewToast.makeText(mContext, e.getCause().getMessage());
                } else {
                    NewToast.makeText(mContext, "获取用户信息失败，请检查网络");
                }
                Log.i(TAG, "onError: " + e);

            }

            @Override
            public void onNext(UserToken mUserToken) {
                if (mUserToken != null) {
                    UserToken m = wirteToken(mUserToken, code);
                    Log.i(TAG, "onNext: " + mUserToken);
                    getMyInfo(m);
                } else {

                }
            }
        };
        HappySaleManager.getInstence().weixinLogin(code, deviceId, mUserSubscriber).subscribe(mUserSubscriber);

    }

    private static void getMyInfo(final UserToken mUserToken) {
        if (mUserInfoSubscriber != null) {
            if (!mUserInfoSubscriber.isUnsubscribed()) {
                mUserInfoSubscriber.unsubscribe();
            }
        }
        mUserInfoSubscriber = new Subscriber<UserInfoResult>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())) {
                    String message = e.getCause().getCause().getMessage();
                    NewToast.makeText(mContext, message);
                    int ret = Integer.valueOf(e.getCause().getMessage());
                    if (ret >= 100 && ret < 200) {
                        LoginOutUtil.logOut(mContext);
                    }
                } else if (HappySaleManager.DATA_NULL.equals(e.getMessage())) {
                    NewToast.makeText(mContext, "返回数据为NULL");
                } else {
                    NewToast.makeText(mContext, "获取用户信息失败，请检查网络");
                }
                Log.i(TAG, "onError: " + e);

            }

            @Override
            public void onNext(UserInfoResult mUserInfoResult) {
                switch (loginPosion) {
                    case 1:
                        LocalUserInfoUtils.deleteUserInfoResult("1");
                        LocalTokenUtils.deleteUserToken("1");
                        boolean m = LocalTokenUtils.insertUserToken(mUserToken);
                        boolean n = LocalUserInfoUtils.insertUserInfoResult(mUserInfoResult);
                        funcTion(mUserToken, mUserInfoResult);
                        break;
                    case 3:
                        LocalUserInfoUtils.updataUserInfoResult(mUserInfoResult, "1");
                        LocalTokenUtils.updataUserToken(mUserToken, "1");
                        funcTion(mUserToken, mUserInfoResult);
                        break;
                    case 2:
                        LocalTokenUtils.updataUserToken(mUserToken, "1");
                        LocalUserInfoUtils.updataUserInfoResult(mUserInfoResult, "1");
                        AppData.getInstence().setmUserInfoResult(mUserInfoResult);
                        AppData.getInstence().setmUserToken(mUserToken);
                        LoginObserable.getInstance().refreshUserSign(0); //通知更新完成
                        break;
                }

            }
        };
        HappySaleManager.getInstence().userInfo(mUserToken.getUserId() + "", mUserToken.getUserSign(), mUserInfoSubscriber).subscribe(mUserInfoSubscriber);
    }

    private static void funcTion(UserToken t, UserInfoResult in) {
        AppData.AppDataBuilder builder = new AppData.AppDataBuilder();
        builder.userInfoResult(in);
        builder.userToken(t);
        builder.build();
        if ("".equals(in.getMobile())) {
            LoginObserable.getInstance().refreshUserSign(1);
        } else {
            if ("-1".equals(in.getRole())) {
                LoginObserable.getInstance().refreshUserSign(2);
            } else {
                LoginObserable.getInstance().refreshUserSign(3);
            }
        }

    }


    private static UserToken wirteToken(UserToken mUserToken, String code) {
        String accessToken = mUserToken.getAccessToken();
        String reflashToken = mUserToken.getReflashToken();
        String signKey = mUserToken.getSignKey();
        int userId = mUserToken.getUserId();
        //accessToken|userId|reflashToken|deviceId
        String userSign = IDEACode.getSignedData(accessToken, userId, reflashToken, deviceId, signKey);
        if (code != null) {
            mUserToken.setCode(code);
        }
        mUserToken.setUserSign(userSign);
        mUserToken.setTokenId("1");
        return mUserToken;
    }


}
